package com.fofia.iotweb.web.dbdomain.services.admin;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fofia.iotweb.Contants.DataStatusEnum;
import com.fofia.iotweb.common.IdHelper;
import com.fofia.iotweb.web.dbdomain.mappers.admin.SysDeptMapper;
import com.fofia.iotweb.web.dbdomain.mappers.admin.SysRoleMapper;
import com.fofia.iotweb.web.dbdomain.mappers.admin.SysUserMapper;
import com.fofia.iotweb.web.dbdomain.models.admin.SysDept;
import com.fofia.iotweb.web.dbdomain.models.admin.SysRole;
import com.fofia.iotweb.web.dbdomain.models.admin.SysUser;
import com.fofia.iotweb.web.dto.DataTableDto;
import com.fofia.iotweb.web.dto.JsonResult;
import com.fofia.iotweb.web.dto.LoginUserDto;
import com.fofia.iotweb.web.dto.ResultAdaptDto;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;


@Component
public class SysUserService {

    @Inject("db")
    private SysUserMapper userMapper;
    @Inject("db")
    private SysDeptMapper deptMapper;
    @Inject("db")
    private SysRoleMapper roleMapper;

    public DataTableDto getPageList(int page, int psize,String loginName,String userName,String phone){


        QueryWrapper queryWrapper=QueryWrapper.create();
        if(!StrUtil.isEmpty(loginName)){
            queryWrapper.where(SysUser::getLoginName).eq(loginName);
        }
        if(!StrUtil.isEmpty(userName)){
            queryWrapper.where(SysUser::getUserName).like(userName);
        }
        if(!StrUtil.isEmpty(phone)){
            queryWrapper.where(SysUser::getMobilePhone).eq(phone);
        }

        queryWrapper.orderBy(SysUser::getIsSuper).desc()
                .orderBy(SysUser::getId).desc();

        Page<SysUser> records=userMapper.paginate(page,psize,queryWrapper);
        var list=records.getRecords();
        //获取用户的角色信息
        Hashtable<Long,String> roleDic=new Hashtable<Long, String>();
         list.forEach(s->{
             if(roleDic.containsKey(s.getRoleId())){
                 s.setRoleName(roleDic.get(s.getRoleId()));
             }else{
                 SysRole role=roleMapper.selectOneById(s.getRoleId());
                 if(role!=null){
                     s.setRoleName(role.getRoleName());
                     roleDic.put(role.getId(),role.getRoleName());
                 }else{
                     roleDic.put(s.getRoleId(),"");
                 }
             }

         });


        DataTableDto  dto=new DataTableDto();
        dto.setRows(list);
        dto.setTotal(records.getTotalRow());
        dto.setPageNumber(page);
        dto.setPageSize(psize);

        return dto;
    }


    public SysUser Login(String loginName,String password){

        QueryWrapper query= QueryWrapper.create()
                .where(StrUtil.format("login_name='{}'",loginName))
                .orderBy(SysUser::getId,false)
                .limit(1);
        SysUser user= userMapper.selectOneByQuery(query);
        if(user!=null){
            if(StrUtil.isEmpty(user.getUserAvatar())){
                user.setUserAvatar("/ui/images/profile.jpg");
            }
        }

        return user;
    }
    public SysUser Login2(String loginName,String password){

        SysUser user=  QueryChain.of(userMapper)
                .where(SysUser::getLoginName).eq(loginName)
                .orderBy(SysUser::getId).desc().limit(1).one();

        if(user!=null){
            if(StrUtil.isEmpty(user.getUserAvatar())){
                user.setUserAvatar("/ui/images/profile.jpg");
            }
        }

        return user;
    }

    /**
     *
     * @author yushuo
     * @description 获取用户信息
     * @date 13:48 2021/2/1
     * @param id
     * @return com.easycms.web.system.domain.SysUser
     **/
    public SysUser getModel(Long id){
        SysUser user= userMapper.selectOneById(id);
//        if(user!=null){
//
////            LambdaQueryWrapper<SysUserPosition> userPLambda=Wrappers.lambdaQuery();
////            userPLambda.eq(SysUserPosition::getUserId,id)
////                    .select(SysUserPosition::getPositionId);
////            List<Long> userPostions=userPositionMapper.selectList(userPLambda).stream().map(SysUserPosition::getPositionId).collect(Collectors.toList());
////            user.setPositionList(userPostions);
//        }

        return user;
    }

    /**
     *
     * @author yushuo
     * @description //判断用户名是否存在
     * @date 10:39 2021/2/1
     * @param dto
     * @return boolean
     **/
    public boolean userExists(SysUser dto){
        QueryWrapper query=QueryWrapper.create()
                .select(SysUser::getId, SysUser::getLoginName)
                 .where(SysUser::getLoginName).eq(dto.getLoginName())
                .limit(0,1);
        SysUser user=userMapper.selectOneByQuery(query);
        if(user==null){
            return false;
        }
        if(user.getId()==dto.getId()){
            return false;
        }
        return true;

    }

    /**
     * 保存用户
     * @param dto
     * @param positions
     * @param userOwnInfo
     */
    public void save(SysUser dto,String[] positions, LoginUserDto userOwnInfo){
        if(dto.getUserStatus()==0){
            dto.setUserStatus(DataStatusEnum.DISABLE.getCode());
        }else{
            dto.setUserStatus(DataStatusEnum.ENABLE.getCode());
        }
        if(dto.getIsSuper()==0){
            dto.setIsSuper(DataStatusEnum.NOT_SUPER.getCode());
        }else{
            dto.setIsSuper(DataStatusEnum.SUPER.getCode());
        }

        if(dto.getDeptId()==0){
            dto.setDeptId(0);
            dto.setDeptName("");
        }else{
            SysDept dept=deptMapper.selectOneById(dto.getDeptId());
            if(dept!=null){
                dto.setDeptName(dept.getDeptName());
            }
        }
        if(dto.getRoleId()==0){
            dto.setRoleId(0L);
        }


        if(StrUtil.isEmpty(dto.getUserAvatar())){
            dto.setUserAvatar("");
        }
        dto.setUpdateTime(DateUtil.date());
        dto.setUpdateBy(userOwnInfo.getLoginName());
        if(dto.getId()==0){
            dto.setId(IdHelper.nextId());
            dto.setDelFlag(DataStatusEnum.NOT_DELETED.getCode());
            dto.setCreateBy(userOwnInfo.getLoginName());
            dto.setCreateTime(DateUtil.date());
            userMapper.insert(dto);
        }else{
            SysUser user=userMapper.selectOneById(dto.getId());
            if(user!=null){
                dto.setDelFlag(user.getDelFlag());
                userMapper.update(dto);
            }
        }

        //插入职位信息
//        LambdaQueryWrapper<SysUserPosition> userPLambda=Wrappers.lambdaQuery();
//        userPLambda.eq(SysUserPosition::getUserId,dto.getId());
//        userPositionMapper.delete(userPLambda);
//        if(positions.length>0){
//            for (String positionId:positions){
//                SysUserPosition userPostion=new SysUserPosition();
//                userPostion.setUserId(dto.getId());
//                userPostion.setPositionId(Convert.toLong(positionId));
//                userPostion.setCreateBy(userOwnInfo.getLoginName());
//                userPostion.setCreateTime(dto.getUpdateTime());
//                userPositionMapper.insert(userPostion);
//            }
//        }
    }

    public void removeAll(String ids){
        List<Long> idArray = Arrays.asList(Convert.toLongArray(ids)) ;
        userMapper.deleteBatchByIds(idArray);

    }

    public ResultAdaptDto updatePassword(long id,String newPassword){
        ResultAdaptDto ret = new ResultAdaptDto();
        SysUser user=getModel(id);
        if(user==null){
            return JsonResult.failure("用户不存在");
        }
        SysUser account = UpdateEntity.of(SysUser.class, id);
        account.setPassWord(newPassword);
        userMapper.update(account);

        return JsonResult.success("密码已更新");
    }

    public ResultAdaptDto updatePorfile(LoginUserDto user){
        SysUser model=getModel(user.getUserId());
        if(user==null){
            return JsonResult.failure("用户不存在");
        }

        if(user.getUserName().isEmpty()){
            return JsonResult.failure("请填写用户名");
        }
        if(user.getEmail().isEmpty()){
           user.setEmail("");
        }
        if(user.getTel().isEmpty()){
           user.setTel("");
        }
        SysUser account = UpdateEntity.of(SysUser.class, user.getUserId());
        account.setUserName(user.getUserName());
        account.setMobilePhone(user.getTel());
        account.setEmail(user.getEmail());
        account.setGender(user.getGender());
        userMapper.update(account);

        return JsonResult.success("个人资料已更新");
    }

    public void updateAvatar(long userId,String avatar){
        SysUser account = UpdateEntity.of(SysUser.class, userId);
        account.setUserAvatar(avatar);
        userMapper.update(account);
    }

}
